package com.tree.lifetree.passport.security;

import com.tree.lifetree.passport.mapper.AdminMapper;
import com.tree.lifetree.passport.pojo.vo.AdminLoginInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private AdminMapper mapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("Spring Security调用了loadUserByUsername()方法，参数：{}", s);

        AdminLoginInfoVO info = mapper.getLoginInfoByUsername(s);
        log.debug("从数据库中通过用户名【{}】查询到的结果为：{}",s,info);

        //判断
        if(info.getUsername().equals(s)){
            UserDetails userDetails = User.builder()
                    .username(info.getUsername())
                    .password(info.getPassword())
                    .disabled(info.getEnable() == 0)//禁用
                    .accountLocked(false)//账号锁定
                    .accountExpired(false)//账号过期
                    .credentialsExpired(false)//凭证过期
                    .authorities("不知道啥权限")//权限
                    .build();
            log.debug("返回的用户详情为:{}", userDetails);
            return userDetails;
        }

        //用户不存在
        return null;
    }
}
